package com.nft.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nft.utils.common.GetPostUntil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


public class WxCode {
    private static WxCode instance;
    public static WxCode getInstance() {
        if (instance == null) {
            instance = new WxCode();
        }
        return instance;
    }

    public String getAccessToken() {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", "wxae0f0d0aef1a8645");
        params.put("APPSECRET", "26fd8e0d4fe102b8e37fc421f1277684");
        ResponseEntity<String> reponseEntity = restTemplate.getForEntity("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = reponseEntity.getBody();
        JSONObject object = JSON.parseObject(body);
        String Access_Token = object.getString("access_token");
        return Access_Token;
    }

    public String getOpenId(String code) {
        String appid = "wxae0f0d0aef1a8645";
        String secret = "26fd8e0d4fe102b8e37fc421f1277684";
        String wxLoginUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
        String param = "appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
        String jsonString = GetPostUntil.sendGet(wxLoginUrl, param);
        JSONObject json = JSONObject.parseObject(jsonString);
        String openid = json.getString("openid");
        return openid;
    }

    public JSONObject wxDecrypt(String encryptedData, String iv, String sessionKey) {
        try {
            // 加密秘钥
            byte[] keyByte = org.apache.commons.codec.binary.Base64.decodeBase64(sessionKey);
            // 偏移量
            byte[] ivByte = org.apache.commons.codec.binary.Base64.decodeBase64(iv);
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + 1;
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters); // 初始化
            // 被加密的数据
            byte[] dataByte = org.apache.commons.codec.binary.Base64.decodeBase64(encryptedData);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, StandardCharsets.UTF_8);
                return JSONObject.parseObject(result);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getMinPhonenumber(String encryptedData, String iv, String sessionKey) {
        JSONObject object = wxDecrypt(encryptedData, iv, sessionKey);
        Object number = object.get("phoneNumber");
        if (null != number) {
            return number.toString();
        }
        return null;
    }

    public com.alibaba.fastjson.JSONObject getMinOpenId(String code) {
        String appid = "wx5bb461aec9a46b52";
        String secret = "cec76eebe76c8095c1012ea683b807df";
        String wxLoginUrl = "https://api.weixin.qq.com/sns/jscode2session";
        String param = "appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
        String jsonString = GetPostUntil.sendGet(wxLoginUrl, param);
        JSONObject json = JSONObject.parseObject(jsonString);
        String openid = json.getString("openid");
        String sessionKey = json.getString("session_key");
        com.alibaba.fastjson.JSONObject result = new com.alibaba.fastjson.JSONObject();
        result.put("openid", openid);
        result.put("sessionKey", sessionKey);
        return result;
    }
}
